/**

This file is part of MaCI/GIMnet.

MaCI/GIMnet is free software: you can redistribute it and/or modify it 
under the terms of the GNU Lesser General Public License as published 
by the Free Software Foundation, either version 3 of the License, or 
(at your option) any later version.

MaCI/GIMnet is distributed in the hope that it will be useful, but WITHOUT 
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public 
License for more details.

You should have received a copy of the GNU Lesser General Public 
License along with GIMnet. (See COPYING.LESSER) If not, see 
<http://www.gnu.org/licenses/>.

**/
/**
 * \file
 * \brief Implementation for Text interface client library.
 * \author Matthieu Myrsky <matthieu.myrsky@tkk.fi>
 */

#include "TextClient.hpp"
#include <float.h>
//*****************************************************************************
using namespace MaCI::Text;
//*****************************************************************************
//*****************************************************************************
#define GIMI_CLIENT_API (20000)
#include "gimi.h"
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
CTextClient::CTextClient(gimi::GIMI *aGIMIPtr, const int aInterfaceMinor)
  : CSync(2,1), 
    CThread(1),
    CMaCI(aGIMIPtr, GIMI_PROTOCOL_MACI_TEXT, aInterfaceMinor),
    iLastTextSaid(),
    iLastTextFromServer(),
    iLastTextReplySeq(0),
    iTextFromServerSeq(0),
    iTextClientCallback(NULL)
{
}    
//*****************************************************************************
      
/** Destructor.
 */
CTextClient::~CTextClient()
{
  DoClose();
}
//*****************************************************************************      

/** Open client interface.
 */
MaCI::EMaCIError CTextClient::DoOpen(void)
{
  MaCI::EMaCIError result = MaCI::KMaCIError;
  
  if(!IsActive()){
    // Do Subs. using the MaCI provided function.
    result = SubscribeToInterface();
    
    // If all inits were fine...
    if(result == KMaCIOK){
      SetActive(true);
      CThread::RunThread();
      result = KMaCIOK;
    }
    
  } else {
    dPrint(3,"Client already opened");

  }

  return result;
}

//*****************************************************************************

/** Close client interface.
 */
MaCI::EMaCIError CTextClient::DoClose(void)
{
  MaCI::EMaCIError result = MaCI::KMaCIError;
  // dPrint(ODTEST,"CTextClient::DoClose() called");
  
  if (CThread::IsThreadRunning()) {
    // Deactivate
    //dPrint(ODTEST,"Deactivate");
    CMaCI::SetActive(false);

    // Unsub
    //dPrint(ODTEST,"UnSub");
    UnsubscribeToInterface(TimeoutValue(2000));

    // Wait for thread to complete.
    //dPrint(ODTEST,"Notify");
    CSync::Notify(KTypeTextFromServer);
    //dPrint(ODTEST,"Notify");
    CSync::Notify(KTypeTextReplyFromServer);
    //dPrint(ODTEST,"Wait");
    CThread::WaitThread();
    //dPrint(ODTEST,"Wait Completed");

    // ok
    result = KMaCIOK;
  } else {
    result = MaCI::KMaCIError;
    
  }

  assert(CThread::IsThreadRunning() == false);
  
  dPrint(3,"CTextClient::DoClose() completed");

  return result;
}
//*****************************************************************************

bool CTextClient::SendText(const std::string &aText,
                           unsigned int aTimeout_ms){

  return SendText(aText);
}
//*****************************************************************************

bool CTextClient::SendText(const std::string &aText)
{
  gim::binbag::CBinBag bb;
  CTextData ttsData;
  ttsData.EncodeTo(&bb);
  ttsData.SetCommand(TCommand(KCommandSendText));
 
  ttsData.SetText(aText);
  ttsData.Print(100);
  const MaCI::EMaCIError e = SendInterfaceMessage(bb.GetBuffer(),
						  bb.GetBufferSize());
  
  return (e == MaCI::KMaCIOK);

}
//*****************************************************************************

bool CTextClient::ClearText(void)
{
  gim::binbag::CBinBag bb;
  CTextData ttsData;
  ttsData.EncodeTo(&bb);
  ttsData.SetCommand(TCommand(KCommandClearText));
  
  const MaCI::EMaCIError e = SendInterfaceMessage(bb.GetBuffer(),
						  bb.GetBufferSize());
  
  return (e == MaCI::KMaCIOK);

}
//*****************************************************************************

bool CTextClient::GetTextAccomplishedEvent(std::string &aText,
                                           int *aSeq,
                                           unsigned int aTimeout_ms)
{
  bool result = false;
  
  Lock();
  
  if (aSeq == NULL) {
    if(iLastTextReplySeq >0){
      //tee stringi
      unsigned int numberOfCharPacks = iLastTextSaid.GetTextHeader()->number;
      for(unsigned int i = 0; i< numberOfCharPacks; i++){
        aText += std::string(iLastTextSaid.GetText(i)->text);
      }
      result = true;
    }
  }else{
    if (iLastTextReplySeq <= *aSeq) {
      int time_left = aTimeout_ms;
      unsigned int time_begin = ownTime_get_ms();
      do {
        Wait(time_left,KTypeTextReplyFromServer);
        time_left = aTimeout_ms - ownTime_get_ms_since(time_begin);
      }while(IsActive() && iLastTextReplySeq < *aSeq &&time_left > 0);
      
      if(iLastTextReplySeq > *aSeq){
        unsigned int numberOfCharPacks = iLastTextSaid.GetTextHeader()->number;
        for(unsigned int i = 0; i< numberOfCharPacks; i++){
          aText += std::string(iLastTextSaid.GetText(i)->text);
        }
        *aSeq = iLastTextReplySeq;
	result = true;
      }else{
	dPrint(4,"Failed to get latest text said (Timeout %dms)",
	       aTimeout_ms);
      }
    }else{
      unsigned int numberOfCharPacks = iLastTextSaid.GetTextHeader()->number;
      for(unsigned int i = 0; i< numberOfCharPacks; i++){
        aText += std::string(iLastTextSaid.GetText(i)->text);
      }
      
      *aSeq = iLastTextReplySeq;
      result = true;
    }
  }
  Unlock();
  return result;

}
//*****************************************************************************

bool CTextClient::GetTextEvent(std::string &aText,
                               int *aSeq,
                               unsigned int aTimeout_ms)
{

  bool result = false;
  
  Lock();
  
  if (aSeq == NULL) {
    if(iTextFromServerSeq >0){
      result =  iLastTextFromServer.GetWholeText(aText);
    }
  }else{
    if (iTextFromServerSeq <= *aSeq) {
      int time_left = aTimeout_ms;
      unsigned int time_begin = ownTime_get_ms();
      do {
        Wait(time_left,KTypeTextFromServer);
        time_left = aTimeout_ms - ownTime_get_ms_since(time_begin);
      }while(IsActive() && iTextFromServerSeq < *aSeq &&time_left > 0);
      
      if(iTextFromServerSeq > *aSeq){
        result =  iLastTextFromServer.GetWholeText(aText);     
        *aSeq = iTextFromServerSeq;
      }else{
	dPrint(4,"Failed to get latest text said (Timeout %dms)",
	       aTimeout_ms);
      }
    }else{
      result =  iLastTextFromServer.GetWholeText(aText);     
      *aSeq = iTextFromServerSeq;
    }
  }
  Unlock();
  return result;

}
//*****************************************************************************

int CTextClient::ThreadFunction(const int aThreadNumber)
{
  int result = 0;
  EMaCIError e;
  gimi::GIMIMessage gmsg;
  
  assert(aThreadNumber == 0);
  assert(iGIMIPtr != NULL);
  
  dPrint(ODTEST, "GIMIMessage handler started");

  // Run as long as the thread should be active
  while(IsActive()) {
    // Call the ReceiveMessage wrapper with 1s timeout
    //  dPrint(ODTEST,"ReceiveInterfaceMessage() call");
    e = ReceiveInterfaceMessage(gmsg, 1000*60*60*25);
    //dPrintLCGreen(ODTEST,"ReceiveInterfaceMessage() complete");
    
    if (e == KMaCIOK) {
      dPrint(4,"Message received from %08x",
             gmsg.getSenderId());
      ProcessMessage(gmsg);


    } else if (e != KMaCITimeout) {
      if(IsActive()){
        // Other error, try to recover by sleeping one second.
        dPrint(3,"ProcessMessage returned error %u and client still active. Trying to recover by sleeping 1000ms ",
               e);
        ownSleep_ms(1000);
      }else{
        //
        dPrint(3,"ProcessMessage returned error %u. Normal situtation because client is already closed",
               e);
      }

    }
  }
  
  //dPrintLCRed(ODTEST, "GIMIMessage handler stopped");

  return result;
}
//*****************************************************************************

int CTextClient::ProcessMessage(const gimi::GIMIMessage &msg)
{
  int result = 0;
  gim::binbag::CBinBag bb;
  CTextData c;
  bool r;


  r = bb.Decode(msg.getData(), msg.getDatalength());

  if (r) {
    // Succesfully decoded as BinBag.
    r = c.DecodeFrom(&bb);
    if (r) {
      // Succesfully decoded as Text
      // Now, Check whether it was Command.
      const TCommand *cmd = c.GetCommand();
      if (cmd) {
        switch(cmd->cmd) {
        case KCommandSendText:{
          dPrint(15,"Text sent from server");
          Lock();
          iLastTextFromServer = c;
          dPrint(15,"Notify");
          Notify(KTypeTextFromServer);
          ++iTextFromServerSeq;
          dPrint(15,"seq at processMessage is now %d", iTextFromServerSeq);
          Unlock();
          dPrint(15,"exit");
          // Call the imageClient callbackhandler if set.
          if(iTextClientCallback){
            std::string s;
            if( c.GetWholeText(s)){
            
              iTextClientCallback->OnTextFromServer(s,
                                                    iTextFromServerSeq,
                                                    *this);
            }
          }
          break;
        }	
	case KReplyTextAccomplished:{
          dPrint(8, "Event received");
          Lock();
	  iLastTextSaid = c;
	  Notify(KTypeTextReplyFromServer);
	  ++iLastTextReplySeq;
	  Unlock();
          if(iTextClientCallback){
            std::string s;
            if(c.GetWholeText(s)){
            
              iTextClientCallback->OnTextReplyFromServer(s,
                                                         iLastTextReplySeq,
                                                         *this);
            }
          }
	  break;
 
        }

	default:
          dPrint(4,"Unidentified command! %d (%x)! Ignore.",
                 cmd->cmd, cmd->cmd);
          break;
        }
      }
    }else{
      dPrint(5,"DecodeFrom failed");
    }
  }else{
    dPrint(5,"Decode failed");
  }


  return result;
}

//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
